var packMonitorTable = function() {
	return {
		init : function() {
			var tableId = "pack_monitor_table";
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';			
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "colClientId",
					"value" : $("#id_colClientId").val().trim()
				});
				aoData.push({
					"name" : "packCode",
					"value" : $("#id_packCode").val().trim()
				});
				aoData.push({
					"name" : "shortName",
					"value" : $("#id_cusName").val().trim()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			
			$('#pack_monitor_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/packDataMonitor/getPackDataList.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return checkBoxDivStr;
					},
					"bSortable" : false
				},
				{
					"data" : "colClientId",
					"bSortable" : false
				}, 
				{
					"data" : "packCode",
					"bSortable" : false,
					"defaultContent" : "",
					"render" : function(data, type, full, meta) {
						 return '<a class="showDetail" style="cursor:pointer;color:blue;" data-toggle="modal">'+data+'</a>';
					}
				},
				{
					"data" : "packModel",
					"bSortable" : false,
					"defaultContent" : ""
				}, 
				{
					"data" : "gatherTime",
					"bSortable" : false,
					"defaultContent" : ""
				}, 
				{
					"data" : "shortName",
					"bSortable" : false,
					"defaultContent" : ""
				}, 
				/*{
					"data" : "province",
					"render" : function(data,type,full,meta) {
						return (full.province?full.province:"")+" "+(full.city?full.city:"");
					},
					"bSortable" : false,
					"defaultContent" : ""
				}, */
				{
					"data" : "areaCode",
					
					"bSortable" : false,
					"defaultContent" : ""
				}, 
				/*{
					"data" : "city",
					"bSortable" : false,
					"defaultContent" : ""
				}, */
				{
					"data" : "enableStr",
					"render" : function(data,type,full,meta) {
						if("有效"==data){
							return "<span class=\"label label-info\">" + data + "</span>";
						}else if("无效"==data){
							return "<span class=\"label label-warning\">" + data + "</span>";
						} else {
							return null;
						}
					},
					"bSortable" : false,
					"defaultContent" : ""
				},
				{
					"data" : "powerFailFlag",
					"bSortable" : false,
					"defaultContent" : "",
					"render" : function(data,type,full,meta) {
						if(full.gatherTime!=null){
							var gatherTime = new Date(Date.parse(full.gatherTime.replace(/-/g, "/")));
							var now =  new Date(Date.parse(full.now.replace(/-/g, "/")));
							var minutes = parseInt((now-gatherTime)/(1000*60));
							if(minutes>=10){
								return "<span class=\"label\">下电</span>";
							}
						}
						if(data&&data!=0){
							return "<span class=\"label label-info\">上电</span>";
						} 
						else if(data == 0&&full.gatherTime!=null){
							var gatherTime = new Date(Date.parse(full.gatherTime.replace(/-/g, "/")));
							var now =  new Date(Date.parse(full.now.replace(/-/g, "/")));
							var seconds = parseInt((now-gatherTime)/(1000));
							if( seconds > (5*60)){
								return "<span class=\"label\">下电</span>";
							}else {
								return "<span class=\"label label-info\">上电</span>";
							}
							
						}
						else {
							return "<span class=\"label\">下电</span>";
						}
					}
				}, 
				{
					"data" : "packStatus",
					"bSortable" : false,
					"render" : function(data,type,full,meta) {
						if("报废"==data){
							return "<span class=\"label label-important\">" + data + "</span>";
						} else {
							return null;
						}
					},
					"defaultContent" : ""
				},
				{
					"data" : "productionDate",
					"bSortable" : false,
                    "render" : function(data,type,full,meta) {
                        if (data) {
                        	return data.substr(0,10);
						}else {
                        	return "";
						}
                    },
					"defaultContent" : ""
				}

				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			//新增弹窗
			$("#update_area").click(function(){
				$("#customer_add_area").text("编辑地区");
				var c = util.getCheckedData("pack_monitor_table");
				if (c.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				$("#areaPkId").val(c[0].pkId);
				$("#cityDiv").citySelect({  
					   nodata: "none",  
				       required: true,  
				       prov:"北京",  
				       city:"东城区",  
				       dist:""  
				}); 
				$("#updateArea").modal({show:true,keyboard:false});
			});

			//保存
			$("#form_area_save").on('click', function(e) {
				e.preventDefault();
				var d = {};
				/*d['province'] = $("#loc_province").find("option:selected").text();
				d['city'] = $("#loc_city").find("option:selected").text();
				d['area'] = $("#county").find("option:selected").text();*/
				d['areaCode'] = $("#areaCode").val();
				d['pkId'] = $("#areaPkId").val();
				var table = $('#pack_monitor_table').DataTable();
				var currentPage =table.page();
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/saveArea.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#areaCode").val('');
							$("#areaPkId").val('');
							$("#form_area_close").click();
							table.page(currentPage).draw('page');
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
						
					}
				});
			});

			$("#update").on('click', function(e) {
				e.preventDefault();
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				$("#pkId").val(d[0].pkId);
				$("#productionDate").val(d[0].productionDate?d[0].productionDate.substr(0,10):'');
				$("#updateProductionDate").modal({show:true,keyboard:false});
			});

			$("#form_company_save").on('click', function(e) {
				e.preventDefault();
				var table = $('#pack_monitor_table').DataTable();
				var currentPage =table.page();
				var d = {};
				d['pkId'] = $("#pkId").val();
				d['productionDateStr'] = $("#productionDate").val()!=''?$("#productionDate").val()+' 00:00:00':'';
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/updateProductionDate.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						debugger
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.page(currentPage).draw('page');
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
						
					}
				});
			});
			
			//查看详情
			$("#pack_monitor_table").on("click", "a.showDetail",function(e){
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else {
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkPackStatus.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {'clientId':d[0].colClientId,
							'packCode':d[0].packCode
						},
						"success" : function(resp) {
							debugger
							if(resp&&resp.gatherTime!=null){
								debugger
								//若电流不为0，但是终端长时间不上传数据，判断为下电状态，判断时间间隔10分钟
								var gatherTime = new Date(Date.parse(resp.gatherTime.replace(/-/g, "/")));
								var now =  new Date(Date.parse(resp.now.replace(/-/g, "/")));
								var minutes = parseInt((now-gatherTime)/(1000*60));
								if(minutes>=10){
									util.showModal("#_alertModal", "电池已下电，请查看历史数据");
									return false;
								}
							}
							if(resp&&resp.el==0&&resp.gatherTime!=null){
								//存在电流为0但是仍然是上电状况，此时判断数据上传时间是否是1分钟以内，若是，则为上电状态
								if(resp.gatherTime!=null){
									var gatherTime = new Date(Date.parse(resp.gatherTime.replace(/-/g, "/")));
									var now =  new Date(Date.parse(resp.now.replace(/-/g, "/")));
									var seconds = parseInt((now-gatherTime)/(1000));
									if(seconds>(5*60)){
										util.showModal("#_alertModal", "电池已下电，请查看历史数据");
										return false;
									}else {
										util.showContent("pages/monitor/packDataMonitor_detail.jsp",{'clientId':d[0].colClientId, 'packCode':d[0].packCode});
									}
								} else {
									util.showModal("#_alertModal", "电池已下电，请查看历史数据");
									return false;
								}
								
							}if(resp&&resp.el==null){
								util.showModal("#_alertModal", "电池已下电，请查看历史数据");
								return false;
							}if(!resp){
								util.showModal("#_alertModal", "电池已下电，请查看历史数据");
								return false;
							} else{
								util.showContent("pages/monitor/packDataMonitor_detail.jsp",{'clientId':d[0].colClientId, 'packCode':d[0].packCode});
							}
						}
					});
				}
			});
			
			//查看历史数据
			$("#view_history_button").on('click',function(){
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else {
					util.showContent("pages/monitor/monitor_history_data.jsp",{'clientId':d[0].colClientId,'packCode':d[0].packCode});
				}
			})
			
			//置为失效
			$("#setUnenable").click(function(e){
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("pack_monitor_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkEnableStatus.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"pkId" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "你确定要置为失效？", "setUnenable_conf");
							}else{
								util.showModal("#_alertModal", "所选记录包含无效或报废记录，请重新选择！");
							}
							
						}
					});
				}
			});
			
			//置为失效
			$("#_confirmModal").on('click', '#setUnenable_conf', function() {
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				var packIds = new Array();
				for (var i = 0;i<d.length;i++) {
					packIds.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setPackUnenable.mvc",
					"dataType" : "json",
					"data" : {
						"packId" : packIds.join(",")	
					},
					"success" : function(resp) {
						if(resp.msg=='error') {
							util.alertMsg("提示", "数据异常，请刷新后重试！");
							return;
						} else {
							rmsBox.notify('success', {msg: '操作成功！'});
							$('#pack_monitor_table').DataTable().draw(true);  
						}
					}
				});
			});
			
			//报废
			$("#setFailure").click(function(){
				d = util.getCheckedData("pack_monitor_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else{
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("pack_monitor_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkFailureStatus.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"pkId" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "你确定该电池报废了吗？", "setFailure_confirm");
							}else{
								util.showModal("#_alertModal", "请选择状态未报废的记录！");
							}
							
						}
					});
				}
			})
			
			//置为报废
			$("#_confirmModal").on('click', '#setFailure_confirm', function() {
				//检查所选择数据状态
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setFailure.mvc",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if("success"==resp){
							rmsBox.notify('success', {msg: '操作成功！'});
							$('#pack_monitor_table').DataTable().draw(true); 
						} else {
							util.alertMsg("提示", "error");
						}
						
					}
				});
			})
			
			
			//打印
			$("#print").click(function(e){
				var d = [];
				d = util.getCheckedData("pack_monitor_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else {
					if ($('#print').attr("href")) {
						$("#print_colClientId").html(d[0].colClientId);
						$("#print_packNum").html(d[0].packCode);
						$("#print_cusName").html(d[0].cusName);
					} else {
						$('#print').attr("href", "#dayin");
						$('#print').click();
					}
				}
			});
			
			// 查询
			$("#btn_query").click(function(e){
				var table = $('#pack_monitor_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").click(function(e){
				$("#pack_search_form")[0].reset();
				$(".select2-selection__rendered").empty();
				$(".select2-selection__rendered").append("<span class='select2-selection__placeholder'>请选择</span>");
			});
			
			//打印确认
			$("#print_confirm").click(function(){
				$("#print_area").jqprint();
			});
			
			$(function(){
				
				util.getOption("main/customer/getCustomerShortNames.mvc", null, "id_cusName");
				$("#id_cusName").select2({
	          	     placeholder:'全部',//默认文字提示
	          	     language: "zh-CN",//汉化
	          	     allowClear: true//允许清空
	          	});
				
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
			
			//离线文件导入
			$("#offline_file_upload").click(function(e){
				$("#greateID").modal("show");
				$("#uploadFile").val("");
			});
			
			$("#confirm_upload").click(function(){
				var doc = $("#uploadFile");
				//文件不为空
				if(doc.val() == "" || doc.val() == null){
					return false;
				}
				/*
				 * 遍历验证所选文件类型及大小 .csv类型 大小不超5m
				 */
				var obj = document.getElementById("uploadFile");
				var length = obj.files.length;
				if(length > 2){
					rmsBox.notify('warning', {msg: '最多选择两个文件！',delay:3000});
					return false;
				}
				for ( var i = 0; i < length; i++) {
					if(obj.files[i].size/1024/1024 > 5){
						rmsBox.notify('warning', {msg: '文件超出5M！',delay:3000});
						return false;
					}
					var temp = obj.files[i].name;
				    if(temp.substring(temp.lastIndexOf(".") + 1) != "csv"){
				    	rmsBox.notify('warning', {msg: '请选择csv文件！',delay:3000});
						return false;
					}
				}
				var options = {
					      url: "main/packDataMonitor/importFile.mvc",
					      success:       showResponse,  //处理完成 
					      error:         function(error) {
					    	  console.log("error");
					    	  App.unblockUI($("#test_upload_div"));//停止loading
					    	  },
					      resetForm:     false,  
					      dataType:      'json' };  
				App.blockUI($("#greateID"));//开始loading
				$("#fileUpload").ajaxSubmit(options); 
				return false;
			})
			
			//执行成功回调函数
			function showResponse(e){
				App.unblockUI($("#greateID"));//停止loading
				$("#greateID").modal("hide");
				if(e.result=="success"){
					rmsBox.notify('success', {msg: '操作成功！'});
				} else {
					rmsBox.notify('warning', {msg: e.result,delay:3000});
				}
			}

		}
	};
}();
